package com.songcha.library_business.handler

import android.graphics.Paint
import com.songcha.library_common.util.FontUtil

class TextSpaceSplitHandler {
    companion object{
        @JvmStatic
        fun handleTextSpaceWrap(content:String,textSize:Float,textWidth:Float):String{
            if(textSize <= 0 || textWidth <= 0) return content
            val spanTextPaint = Paint()
            spanTextPaint.isAntiAlias = true
            spanTextPaint.textSize = textSize
            var curPos = 0
            var sb = StringBuffer()
            while(curPos < content.length - 1){
                val singleText = content.substring(curPos,content.length)
                //val mw = FloatArray(2)
                //breakText has a bug
                val singleTextCount = FontUtil.breakText(singleText,textWidth,spanTextPaint) //spanTextPaint.breakText(singleText,false,textWidth,mw)
                if(singleTextCount == singleText.length || singleTextCount == 0){
                    if(singleText.endsWith(" ")){
                        sb.append(singleText.substring(0,singleText.length - 1))
                    }else{
                        sb.append(singleText)
                    }
                    break
                }
                var str = content.substring(curPos,curPos + singleTextCount)
                if(str.endsWith(" ")){
                    str = str.substring(0,str.length - 1)
                    curPos += singleTextCount
                }else{
                    //find pre word
                    val lastIdx = str.lastIndexOf(" ")
                    if(lastIdx == -1){
                        sb.append(singleText)
                        break
                    }
                    val emptyLastPos = str.length - lastIdx
                    str = str.substring(0,str.length - emptyLastPos)
                    curPos = curPos + singleTextCount - (emptyLastPos - 1)
                }
                sb.append(str + "\n")
            }
            return sb.toString()
        }
    }
}